package com.car.action.api;

import java.util.List;
import java.util.Map;

import org.apache.commons.compress.utils.Lists;

import com.car.action.util.CommonController;
import com.car.common.model.UserAlbums;
import com.car.intercept.AdminInterceptor;
import com.car.intercept.ApiCommonInterceptor;
import com.car.job.TheadImgCheck;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.utils.APIJSON;
import com.utils.PicUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;

public class AlbumsController extends CommonController{

	public void get() {
		int user_id = 0;
	    if(StringUtil.empty(getPara("user_id"))){
	    	user_id = getUserId().intValue();
        }else{
            user_id = getParaToInt("user_id");
        }
	    // status = 1 and 
		List<UserAlbums> albumsList = UserAlbums.dao.find("select id,img,status from user_albums where user_id = " + user_id);
		List<Map<String,Object>> albums_list = Lists.newArrayList();
		
		for(UserAlbums one : albumsList) {
			one.setImg(PicUtil.QINIU_DIR + one.getImg());
			Map<String, Object> temp = Maps.newHashMap();
			temp.put("id", one.getId());
			temp.put("img", one.getImg());
			temp.put("status", one.getStatus());
			albums_list.add(temp);
		}
		Map<String,Object> result = Maps.newHashMap();
		result.put("thumb_album", albums_list);
//		result.put("all_album", albums_list);
		/*
		if (albumsList.size() > 4) {
			result.put("thumb_album", albums_list.subList(0, 4));
		} else {
			result.put("thumb_album", albums_list);
		}
		*/
	
		renderText(APIJSON.send(result));
	}
	
	
	/**
     * 新增相册图片
     */
	@Before(ApiCommonInterceptor.class)
	public void add() {
		String img = getPara("img");
		if (StringUtil.empty(img)) {
			renderText(APIJSON.result(4001));
		} else {
			Long user_id = super.getUserId();
			UserAlbums one = new UserAlbums();
			one.setImg(img);
			one.setStatus(2);
			one.setUserId(user_id.intValue());
			one.setCreateTime(SystemClock.now()/1000L);
        	one.setUpdateTime(SystemClock.now()/1000L);
        	one.save();
        	Map<String,Object> handleData = Maps.newHashMap(); 
    		handleData.put("relation_id", one.getId());
    		handleData.put("img", new String[] {img});
    		handleData.put("type", 4);
    		new Thread(new TheadImgCheck(handleData)).start();
    		
        	Map<String,Object> result = Maps.newHashMap();
        	result.put("id", one.getId());
        	result.put("img", PicUtil.QINIU_DIR + img);
        	result.put("status", 1);
        	renderText(APIJSON.send(result));
		}
	}
	
	/**
     * 删除相册图片
     */
	@Before(ApiCommonInterceptor.class)
	public void del() {
		Long user_id = super.getUserId();
		Db.delete("delete from user_albums where id = " + getPara("id") + " and user_id  = " + user_id);
		renderText(APIJSON.result(0));
	}
}
